<?php
/* SVN FILE: $Id: app_model.php 4407 2007-02-02 10:39:45Z phpnut $ */

/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
 * Copyright 2005-2007, Cake Software Foundation, Inc.
 *								1785 E. Sahara Avenue, Suite 490-204
 *								Las Vegas, Nevada 89104
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright		Copyright 2005-2007, Cake Software Foundation, Inc.
 * @link				http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
 * @package			cake
 * @subpackage		cake.app
 * @since			CakePHP(tm) v 0.2.9
 * @version			$Revision: 4407 $
 * @modifiedby		$LastChangedBy: phpnut $
 * @lastmodified	$Date: 2007-02-02 04:39:45 -0600 (Fri, 02 Feb 2007) $
 * @license			http://www.opensource.org/licenses/mit-license.php The MIT License
 */
 
 /**
 * Validation methods are defined in Validation class in validation.php.
 */
	require_once ('validation.php');
	
/**
 * Constants are defined in .php.
 */
	require_once ('debug.php');


/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package		cake
 * @subpackage	cake.app
 */
class AppModel extends Model{

/**
 * For Transaction behavior
 */
	var $actsAs   = array('transaction');

/**
 * Custom Field Invalidation function
 * Called 
 *
 * @return void
 */	
    
   function invalidFields($data= array ())
    {
		// Initialize errors array to a new array
        $this->validationErrors = array();       
       
        // Call beforeValidate() firsthand
        if (!$this->beforeValidate())
        {
            return false;
        }

        // If $data parameter is empty, then we must be validating against the member variable
        // $this->data
        if (empty($data))
        {
            $data = $this->data;
        }
       
        // If $this->validate is not set, nothing to do
        if (!isset($this->validate))
        {
            return true;
        }       

        // PHP <5.0 does not automatically return a reference on new, so here
        $validation =& new Validation($data, $this);
       
        // Iterate over the fields to be validated
        foreach ($this->validate as $fieldName => $validators)
        {
            // If no validators defined, nothing to do
            if (empty($validators) || !is_array($validators))
            {
                continue;
            }

            // Iterate over validators array
            foreach ($validators as $name => $validator)
            {
                // For instances such as:
                // 'field' => array('custom_method' => array('method' => 'validationMethodName'))
                if (is_array($validator) && isset($validator['method']) && $name != 'method')
                {
                    $methodName = $validator['method'];
                    $parameters = $validator;
                    unset($parameters['method']);
                }
                // For instances such as: 'field' => array('unique', 'confirmed', 'number')
                else if (is_string($validator))
                {
                    $methodName = 'validate' . Inflector::camelize($validator);
                    $parameters = array();
                }
                // For instances such as: 'field' => array('range' => array('min' => 5))
                else
                {
                    $methodName = 'validate' . Inflector::camelize($name);
                    $parameters = $validator;
                }
               
                // Set defaul 'on' parameter value to null, meaning this validation will occur both
                // during record creation and update
                if (!isset($parameters['on']))
                {
                    $parameters['on'] = null;
                }
               
                // Skip validation if on create and record is not new; will only occur on new records
                if ($parameters['on'] == 'create' and !empty($this->data[$this->name][$this->primaryKey]))
                {
                    continue;
                }
                   
                // Skip validation if on update and record is new; will only occur on saved records
                if ($parameters['on'] == 'update' and empty($this->data[$this->name][$this->primaryKey]))
                {
                    continue;
                } 
               
                // Set default 'allowNull' parameter to true, meaning validation will return as
                // successfull if field value is null; otherwise, it will proceed with the regular
                // validation process
                if (!isset($parameters['allowNull']))
                {
                    $parameters['allowNull'] = true;
                }
               
                // If field is empty but is not required, skip validation
                if (empty($data[$this->name][$fieldName])
                    and $methodName != 'validateNotEmpty'
                    and $methodName != 'validateRequired'
                    and $parameters['allowNull'] === true)
                {
                    continue;
                }

                // Set field value to null if not present
                if (!isset($data[$this->name][$fieldName]))
                {
                    $data[$this->name][$fieldName] = null;
                }

                // Call method in Validation object if it exists; otherwise, consider it as a
                // regex expression (backwards-compatibility crap)
                if (method_exists($validation, $methodName))
                {
                    $result = call_user_func(array($validation, $methodName), $fieldName, $parameters);
                   
                    if (!$result)
                    {
                        // Nothing to do, error messages have already been added in Validation::_evaluate()
                    }
                }
                else
                {
                    if (!preg_match($methodName, $data[$this->name][$fieldName]))
                    {
                        $this->validationErrors[$fieldName][$name] = 1;
                    }
                }
            }

        }
       
        return $this->validationErrors;
    }

   // Custom validation function to check whether the value of a field in model exists
	function isEntryExist($field, $value){
        $fields[$this->name.'.'.$field] = $value;
        $this->recursive = -1;
        if ($this->hasAny($fields)){
            return true;
        } else {
            return true;
		}
	}
	
	/**
	 * Before save callback
	 *
	 */
	function beforeSave() {
		
		$excludeModels = array("User", "Aro", "Aco", "ArosAco", "Pages", "TableStatus");
		if (!in_array($this->name, $excludeModels)) {
		
			if (!array_key_exists('id', $this->data[$this->name])) {
				if (!$this->id) {
					$this->data[$this->name]['id'] = $this->nextInsertId;
				} else {
					$this->data[$this->name]['id'] = $this->id;
				}
			}
			if($this->data[$this->name]['id'] == null) {
				$this->data[$this->name]['id'] = $this->nextInsertId;
			}
		}
		//debug($this->data);
		return parent::beforeSave();
		
	}
	
	/**
	 * After save callback
	 *
	 * @return unknown
	 */
	function afterSave() {
		
		$excludeModels = array("User", "Aro", "Aco", "ArosAco", "Pages");
		if (!in_array($this->name, $excludeModels)) {
			$this->nextInsertId++;
		}
		
		return parent::afterSave();
				
	}
	
}
?>